<?php
Yii::import('ext.multimodelform.MultiModelForm');
class MakananController extends RController
{
	private $model; //Post
	private $transaction; //CDbTransaction
	private $validatedPostIngredient = array();
	private $deleteItems = array();
	
	public function init(){
		$this->model = new Post;
		$this->transaction = Yii::app()->db->beginTransaction();
	}
	
	public function filters()
	{
		return array(
			'rights',
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	public function savePost(){
		$postIngredient = new PostIngredient;
		$this->validatedPostIngredient = array();
		
		if (isset($_POST['Post'])) {
			$this->model->attributes=$_POST['Post'];
			$validate = MultiModelForm::validate($postIngredient, $this->validatedPostIngredient, $this->deleteItems);
			
			if ($validate && $this->model->saveIncludingCategories())
			{
				$masterValue = array('post_id'=>$this->model->id);
				if(MultiModelForm::save($postIngredient, $this->validatedPostIngredient, $this->deleteItems, $masterValue)){
					$this->savePhotos(array('image_header','image_excerpt'),$this->model,Yii::app()->params['makananPath']);
					$this->transaction->commit();
					$this->redirect(array('view','id'=>$this->model->id));
				}else
				{
					$this->transaction->rollback();
				}
			}
		}
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		try{
			$this->savePost();
		}catch(Exception $e){
			$this->model->addError('id',$e->getMessage());
			$this->transaction->rollback();
		}
		
		$listSatuan = Satuan::model()->findAll();
		$postIngredientAttr = PostIngredient::model()->attributeLabels();
		$listKategori = Category::model()->findAll();
		$selectedValues = PostCategory::model()->findAllByAttributes(array('post_id'=>$this->model->id));

		$this->render('create',array(
			'model'=>$this->model,
			'listSatuan'=>$listSatuan,
			'postIngredientAttr'=>$postIngredientAttr,
			'validatedPostIngredient'=>$this->validatedPostIngredient,
			'listKategori'=>$listKategori,
			'selectedValues'=>$selectedValues,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$this->model = $this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		try{
			$this->savePost();
		}catch(Exception $e){
			$this->model->addError('id',$e->getMessage());
			$this->transaction->rollback();
		}
		
		$listSatuan = Satuan::model()->findAll();
		$postIngredientAttr = PostIngredient::model()->attributeLabels();
		$listKategori = Category::model()->findAll();
		$selectedValues = PostCategory::model()->with('category')->findAllByAttributes(array('post_id'=>$this->model->id));
		$selectedValues = CHtml::listData($selectedValues,'category.nama','category.nama');

		$this->render('create',array(
			'model'=>$this->model,
			'listSatuan'=>$listSatuan,
			'postIngredientAttr'=>$postIngredientAttr,
			'validatedPostIngredient'=>$this->validatedPostIngredient,
			'listKategori'=>$listKategori,
			'selectedValues'=>$selectedValues,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax'])) {
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
			}
		} else {
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Post');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Post('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Post'])) {
			$model->attributes=$_GET['Post'];
		}

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Post the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$this->model=Post::model()->findByPk($id);
		if ($this->model===null) {
			throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Post $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if (isset($_POST['ajax']) && $_POST['ajax']==='post-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}